package com.hontech.pastacooking.activity.fragment.sub

import android.view.View
import android.widget.Button
import com.hontech.pastacooking.R
import com.hontech.pastacooking.activity.window.ProgWindow
import com.hontech.pastacooking.activity.window.showProg
import com.hontech.pastacooking.app.bus
import com.hontech.pastacooking.app.onClick
import com.hontech.pastacooking.conn.*
import com.hontech.pastacooking.event.CookProgEvent
import com.hontech.pastacooking.net.NetClient
import com.hontech.pastacooking.net.OrderReq
import com.hontech.pastacooking.net.REQ_ORDER
import com.hontech.pastacooking.serial.UInt8
import kotlinx.coroutines.delay
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class TestCookingDelegate (view: View) {

    private val mBtnBegin = view.findViewById<Button>(R.id.id_btn_start_test_cooking)
    private val btnTestHeatDoor = view.findViewById<Button>(R.id.id_btn_start_test_heat_door)
    private val btnTestUpdown = view.findViewById<Button>(R.id.id_btn_test_updown)

    init {
        mBtnBegin.onClick(::onClickBegin)
        btnTestHeatDoor.onClick(::onClickHeatDoor)
        btnTestUpdown.onClick(::onClickTestUpdown)
    }

    private var dialog: ProgWindow? = null
    private var col = 1
    private var row = 1
    private val msgBuf = StringBuilder()


    private suspend fun onClickTestUpdown() {

        val dialog = showProg(mBtnBegin, "测试升降")
        var count = 0

        try {
            thawCleanCtrl(THAW_CLEAN_DISABLE_FOREVER)

            while (true) {
                dialog.show(mBtnBegin, "第:${count+1}次 机器复位")
                deviceReset()

                requestMain(
                    60 * 1000,
                    MainProto.TestCargoFetch,
                    arrayOf(UInt8(2)),
                    "中间"
                )

                for (i in 0 until 50) {
                    dialog.show(mBtnBegin, "第:${count+1}次 第${i+1}次上升")

                    requestMain(
                        20 * 1000,
                        MainProto.TestCargoElevator,
                        arrayOf(UInt8(1), UInt8(10)),
                        "升到第十层")
                    if (!dialog.isShow) {
                        return
                    }

                    delay(2000)
                    dialog.show(mBtnBegin, "第:${count+1}次 第${i+1}次下降")

                    requestMain(
                        20 * 1000,
                        MainProto.TestCargoElevator,
                        arrayOf(UInt8(1), UInt8(1)),
                        "升到第一层"
                    )
                    if (!dialog.isShow) {
                        return
                    }
                }

                dialog.show(mBtnBegin, "第:${count+1}次 转左边")
                requestMain(
                    60 * 1000,
                    MainProto.TestCargoFetch,
                    arrayOf(UInt8(1)),
                    "左边"
                )
                if (!dialog.isShow) {
                    return
                }

                dialog.show(mBtnBegin, "第:${count+1}次 转右边")
                requestMain(
                    60 * 1000,
                    MainProto.TestCargoFetch,
                    arrayOf(UInt8(2)),
                    "中间"
                )
                if (!dialog.isShow) {
                    return
                }

                for (i in 0 until 10) {
                    dialog.show(mBtnBegin, "第:${count+1}次 升到第:${i+1}层")

                    requestMain(
                        20 * 1000,
                        MainProto.TestCargoElevator,
                        arrayOf(UInt8(1), UInt8(i + 1)),
                        "升到:${i + 1}层"
                    )
                    if (!dialog.isShow) {
                        return
                    }

                    delay(3000)
                }

                dialog.show(mBtnBegin, "第:${count+1}次 转左边2")
                requestMain(
                    60 * 1000,
                    MainProto.TestCargoFetch, arrayOf(UInt8(1)),
                    "左边"
                )
                if (!dialog.isShow) {
                    return
                }

                dialog.show(mBtnBegin, "第:${count+1}次 转中间2")
                requestMain(
                    60 * 1000,
                    MainProto.TestCargoFetch, arrayOf(UInt8(2)),
                    "中间"
                )
                if (!dialog.isShow) {
                    return
                }

                count += 1
            }

        } catch (e: Exception) {
            e.printStackTrace()
            dialog.error("测试次数:$count ${e.message}")
        } finally {
            try {
                thawCleanCtrl(THAW_CLEAN_ENABLE)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    private fun next() {
        row ++
        if (row >= 10) {
            col ++
            row = 1
        }
        if (col >= 5) {
            col = 1
            row = 1
        }
    }

    private suspend fun heatDoorOpen() {
        requestMain(15 * 1000, MainProto.TestHeatDoor, arrayOf(UInt8(0)), "保温门打开")
    }

    private suspend fun heatDoorClose() {
        requestMain(15 * 1000, MainProto.TestHeatDoor, arrayOf(UInt8(1)), "保温门关闭")
    }

    private suspend fun onClickHeatDoor() {

        val dialog = showProg(mBtnBegin, "测试保温门")
        var count = 0
        try {

            thawCleanCtrl(THAW_CLEAN_DISABLE_FOREVER)

            for (i in 0 until 30000) {
                count = i
                dialog.show(mBtnBegin, "保温门打开 $count")
                heatDoorOpen()
                if (!dialog.isShow) {
                    break
                }
                delay(1000)

                dialog.show(mBtnBegin, "保温门关闭 $count")
                heatDoorClose()
                if (!dialog.isShow) {
                    break
                }
                delay(1000)
            }

        } catch (e: Exception) {
            e.printStackTrace()
            dialog.error("测试次数:$count ${e.message}")
        }

        try {
            thawCleanCtrl(THAW_CLEAN_ENABLE)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onNotify(env: CookProgEvent) {
        val dialog = dialog ?: return
        if (!dialog.isShow) {
            return
        }
        dialog.show(mBtnBegin, "${col}-${row} ${env.msg}")
        msgBuf.appendLine(env.msg)
    }

    private fun sendToServer(duration: Long) {
        val msg = "${col}-${row} $msgBuf"
        val req = OrderReq(msg, duration)
        NetClient.notifyObj(REQ_ORDER, req)
    }

    private suspend fun onClickBegin() {

        try {
            thawCleanCtrl(THAW_CLEAN_DISABLE_FOREVER)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        bus.register(this)

        val dialog = showProg(mBtnBegin, "测试煮面中")
        this.dialog = dialog

        while (true) {

            msgBuf.clear()
            val begin = System.currentTimeMillis()

            try {
                testCooking(col, row)
                next()
                if (!dialog.isShow) {
                    break
                }
            } catch (e: Exception) {
                e.printStackTrace()
                val msg = e.message!!
                dialog.error(msg)
                msgBuf.appendLine(msg)
                break
            } finally {
                val duration = System.currentTimeMillis() - begin
                sendToServer(duration / 1000)
            }
        }
        bus.unregister(this)

        try {
            thawCleanCtrl(THAW_CLEAN_ENABLE)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


}
